package com.bootdo.clouddo.utils.book;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class BookUtils {

    public static String getContent(String chapterUrl, Integer siteId) {
        try {
            //chapterUrl = "http://www.iqiwx.com/book/7/7367/9045075.html";
            //siteId = "35";
            // 获取html内容
            String html;
            switch (siteId) {
                case 2: { // 看书神站
                    return getHtmlResult(chapterUrl, null, "class:articleCon");
                }
                case 8: { // 大家读书院
                    return getHtmlResult(chapterUrl, "gbk", "id:content1");
                }
                case 9: { // 番茄小说网
                    return getHtmlResult(chapterUrl, "gbk", "id:content");
                }
                case 11: { // 新笔趣阁
                    return getHtmlResult(chapterUrl, "utf-8", "id:content");
                }
                case 12: { // 少年文学网
                    return getHtmlResult(chapterUrl, "gbk", "id:BookText");
                }
                case 13: { // UC书盟- 待测试
                    if(!chapterUrl.contains("https")) {
                        chapterUrl = chapterUrl.replace("http", "https");
                    }
                    return getHtmlResult(chapterUrl, "gbk", "id:content");
                }
                case 14: { // 小说啦
                    return getHtmlResult(chapterUrl, "gbk", "id:content");
                }
                case 15: { // 书TXT-顶点小说
                    return getHtmlResult(chapterUrl, "gbk", "id:content");
                }
                case 16:   // 顶点NET
                case 18: { // 品书网 https://www.vodtw.com
                    return getHtmlResult(chapterUrl, "gbk", "id:BookText");
                }
                case 21: { // 万万册小说网
                    return getHtmlResult(chapterUrl, "utf-8", "id:nr");
                }
                case 24: { // 乡村小说网
                    return getHtmlResult(chapterUrl, "gbk", "class:yd_text2");
                }
                case 35: { // 爱奇文学
                    return getHtmlResult(chapterUrl, "gbk", "id:content");
                }
                case 10:
                case 36: { // 看书阁
                    return getHtmlResult(chapterUrl, "gbk", "id:BookText");
                }
                case 38: { // 奇书网
                    return getHtmlResult(chapterUrl, "utf-8", "id:content1");
                }
                case 44: {  // 顶点小说，http://www.ddxsku.com
                    return getHtmlResult(chapterUrl, "utf-8", "id:contents");
                }
                default: {}
            }
            // 根据siteId解析html
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getHtmlResult(String url, String charset, String contentTag) throws Exception{
        String html = HttpUtils.doGet(url, charset).getBody();
        if(StringUtils.isBlank(html)) {
            return null;
        }
        String[] contentTags = contentTag.split(":");
        Element doc = Jsoup.parse(html);
        Element content = getContent(doc, contentTags);
        return content.html();
    }

    private static Element getContent(Element doc, String[] contentTag){
        if("id".equals(contentTag[0])) {
            return doc.getElementById(contentTag[1]);
        }else if("class".equals(contentTag[0])) {
            return doc.getElementsByClass(contentTag[1]).first();
        }
        return null;
    }

    public static JSONObject fetchJSONObject(String url) {
        return fetchJSONObject(url, new HashMap<>());
    }

    public static JSONObject fetchJSONObject(String url, Map<String, String> params) {
        try {
            JSONObject jo = fetchDats(url, params);
            if(jo != null || jo.getJSONObject("data") == null) {
                return jo.getJSONObject("data");
            }else{
                System.out.println("url: "+ url + ", fetchJSONObject: " + JSON.toJSONString(jo));
            }
        }catch (Exception e) {
            System.out.println("load data err from:" + url);
        }
        return null;
    }

    public static JSONArray fetchJSONArray(String url, Map<String, String> params) {
        JSONObject jo = fetchDats(url, params);
        if(jo != null) {
            return jo.getJSONArray("data");
        }else{
            System.out.println("fetchJSONArray:" + JSON.toJSONString(jo));
        }
        return null;
    }

    public static JSONArray fetchJSONArray(String url) {
        return fetchJSONArray(url, new HashMap<>());
    }

    public static String fetchString(String url) {
        return fetchString(url, new HashMap<>());
    }

    public static JSONObject fetchDats(String url, Map<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        if(params != null && params.size() > 0)
            url = url + "?" + parseParams(params);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<JSONObject> response = client.exchange(url, method, requestEntity, JSONObject.class);

        return response.getBody();
    }

    public static String fetchString(String url, Map<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        if(params != null && params.size() > 0)
            url = url + "?" + parseParams(params);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);

        return response.getBody();
    }

    public static String parseParams(Map<String, ?> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        for (String key : params.keySet()) {
            sb.append(key + "=" + params.get(key) + "&");
        }
        return sb.substring(0, sb.length() - 1);

    }
}
